package com.aiti.lulian.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.ShowServiceEnterpriseDto;
import com.aiti.lulian.entity.ShowEnterpriseServiceEntity;
import com.aiti.lulian.entity.ShowServiceEnterprise;
import com.aiti.lulian.entity.SysArea;
import com.aiti.lulian.entity.excel.ShowServiceEnterpriseImport;
import com.aiti.lulian.gxmh.service.GxmhServerServicesService;
import com.aiti.lulian.mapper.ShowServiceEnterpriseMapper;
import com.aiti.lulian.mapper.SysAreaMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.service.IShowEnterpriseServiceService;
import com.aiti.lulian.service.ShowServiceEnterpriseService;
import com.aiti.lulian.vo.ShowServiceEnterpriseVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务企业 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-06-13
 */
@Service
public class ShowServiceEnterpriseServiceImpl extends ServiceImpl<ShowServiceEnterpriseMapper, ShowServiceEnterprise> implements ShowServiceEnterpriseService {

    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Autowired
    private IShowEnterpriseServiceService showEnterpriseServiceService;
    @Autowired
    private GxmhServerServicesService gxmhServerServicesService;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;

    @Override
    public List<ShowServiceEnterpriseVo> serviceEnterprisePage(Page page, ShowServiceEnterpriseDto dto) {

        return this.getBaseMapper().serviceEnterprisePage(page, dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message importBatch(MultipartFile file, String userId) throws IOException {
        // 构建报错信息集
        List<String> msgList = new ArrayList<>();
        // 读取数据
        List<ShowServiceEnterpriseImport> serviceEnterpriseImportList = EasyExcel.read(file.getInputStream()).head(ShowServiceEnterpriseImport.class).headRowNumber(1).sheet("服务企业").doReadSync();
        if (serviceEnterpriseImportList == null) {
            return Message.fail("请正确上传文件");
        }
        if (serviceEnterpriseImportList != null && serviceEnterpriseImportList.size() == 0) {
            return Message.fail("尚未读取到数据");
        }
        List<ShowServiceEnterprise> serviceEnterprises = new ArrayList<>();
        for (ShowServiceEnterpriseImport serviceEnterpriseImport : serviceEnterpriseImportList) {
            if (StrUtil.isBlank(serviceEnterpriseImport.getBaseName())) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：企业名称不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(serviceEnterpriseImport.getContactName())) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：联系人不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(serviceEnterpriseImport.getTelephone())) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：联系电话不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(serviceEnterpriseImport.getAddress())) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：企业地址不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(serviceEnterpriseImport.getCity())) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：所在地市不能为空<br/>");
                continue;
            }
            if (StrUtil.isBlank(serviceEnterpriseImport.getCounty())) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：所在区县不能为空<br/>");
                continue;
            }
            ShowServiceEnterprise showServiceEnterprise = new ShowServiceEnterprise();
            showServiceEnterprise.setBaseName(serviceEnterpriseImport.getBaseName());
            showServiceEnterprise.setContactName(serviceEnterpriseImport.getContactName());
            showServiceEnterprise.setTelephone(serviceEnterpriseImport.getTelephone());
            showServiceEnterprise.setAddress(serviceEnterpriseImport.getAddress());
            SysArea city = sysAreaMapper.selectOne(new LambdaQueryWrapper<SysArea>().eq(SysArea::getBaseName, serviceEnterpriseImport.getCity()));
            if (city == null) {
                msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：所在地市尚未查询到<br/>");
                continue;
            } else {
                showServiceEnterprise.setCity(city.getBaseId());
                SysArea county = sysAreaMapper.selectOne(new LambdaQueryWrapper<SysArea>().eq(SysArea::getBaseName, serviceEnterpriseImport.getCounty()).eq(SysArea::getBaseParentId, city.getBaseId()));
                if (county == null) {
                    msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：所在区县尚未查询到<br/>");
                    continue;
                } else {
                    showServiceEnterprise.setCounty(county.getBaseId());
                    if (! StrUtil.isBlank(serviceEnterpriseImport.getStreet())) {
                        SysArea street = sysAreaMapper.selectOne(new LambdaQueryWrapper<SysArea>().eq(SysArea::getBaseName, serviceEnterpriseImport.getStreet()).eq(SysArea::getBaseParentId, county.getBaseId()));
                        if (street == null) {
                            msgList.add("第" + (serviceEnterpriseImportList.indexOf(serviceEnterpriseImport) + 1) + "条：所在街道尚未查询到<br/>");
                            continue;
                        } else {
                            showServiceEnterprise.setStreet(street.getBaseId());
                        }
                    }
                }
            }
            showServiceEnterprise.setCreator(userId);
            showServiceEnterprise.setBaseCreateTime(new Date());
            serviceEnterprises.add(showServiceEnterprise);
        }
        if (serviceEnterprises.size() > 0) {
            this.saveBatch(serviceEnterprises);
        }
        if (msgList.size() > 0) {
            return Message.fail("以下数据导入失败：<br/>" + msgList.stream().collect(Collectors.joining("")));
        } else {
            return Message.success("导入成功");
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Message updateServiceEnterprise(ShowServiceEnterprise entity) {
        this.updateById(entity);
        List<ShowEnterpriseServiceEntity> enterpriseServiceList = showEnterpriseServiceService.list(new LambdaQueryWrapper<ShowEnterpriseServiceEntity>().eq(ShowEnterpriseServiceEntity::getEnterpriseId, entity.getBaseId()).eq(ShowEnterpriseServiceEntity::getIsDelete, false));
        if (enterpriseServiceList.size() > 0) {
            List<ShowEnterpriseServiceEntity> updatedList = enterpriseServiceList.stream().peek(k -> {
                k.setTelephone(entity.getTelephone());
                k.setLogo(entity.getLogo());
                k.setAddress(entity.getAddress());
                k.setEnterpriseName(entity.getBaseName());
            }).collect(Collectors.toList());
            showEnterpriseServiceService.updateBatchById(updatedList);
        }
        return Message.success();
    }
}
